<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" width="930px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" label-width="100px" :rules="rules" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref='name' style="width:300px;" size='small'></el-input>
        </el-form-item>
        <div style="margin-top:20px" class="urlScrollbar">
          <el-table ref="multipleTable" size='mini' :data="urlClassList" @selection-change="autoDetectChange" border>
            <el-table-column type="selection" align='center' width="55"></el-table-column>
            <el-table-column prop="name" align='center' :label="$t('名称')" min-width="150">
            </el-table-column>
            <el-table-column prop="action" align="center" :label="$t('动作')" min-width="120">
              <template slot-scope="scope">
                <el-select v-model="scope.row.action" :ref="'action' + (scope.$index + 1)" size='mini'>
                  <el-option v-for="item in actionTypeList" :key="item.value" :label="$t(item.label)" :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="desc" align='left' label="" min-width="500">
              <template slot-scope="scope">
                <tooltip :copyText="scope.row.desc" class="wid190">
                </tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addUrl, editUrl, getUrlClassArray } from '@/api/safe/url'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'UrlPolicyDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        id: null,
        name: '',
        class_map: ''
      },
      recordCopy: {
        id: null,
        name: '',
        class_map: ''
      },
      urlList: [],
      urlClassList: [],
      loading: false,
      actionTypeList: [ //   alert/deny  告警/阻断
        { value: 'access', label: '允许', id: 0 },
        { value: 'alert', label: '告警', id: 1 },
        { value: 'deny', label: '阻断', id: 2 }
      ],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['name']
        inputClass(this.$refs, data)
      })
      this.loading = true
      getUrlClassArray().then(res => {
        if (res.status === 0) {
          var form = res.info
          for (let item of form) {
            item.action = 'access'
          }
          this.urlClassList = form
          if (!data) {
            this.$nextTick(() => {
              this.urlClassList.forEach((row, ind) => {
                this.$refs.multipleTable.toggleRowSelection(row)
                const selectData = ['action' + (ind + 1)]
                selectClass(this.$refs, selectData)
              })
            })
          } else {
            this.record.name = data.name
            this.record.id = data.id
            this.$nextTick(() => {
              for (let item of data.class_map) {
                for (let url of this.urlClassList) {
                  if (item.class_name === url.name) {
                    var urlAdd = url
                    urlAdd.action = item.action
                    this.$refs.multipleTable.toggleRowSelection(urlAdd)
                    break
                  }
                }
              }
            })
          }
          this.loading = false
        } else {
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    },
    autoDetectChange (data) {
      this.urlList = data
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.urlList.length) {
            this.record.class_map = ''
            this.urlList.forEach(val => {
              this.actionTypeList.forEach(item => {
                if (item.value === val.action) {
                  this.record.class_map += val.id + '-' + item.id + ','
                }
              })
            })
            if (this.record.class_map.lastIndexOf(',') === this.record.class_map.length - 1) {
              this.record.class_map = this.record.class_map.substring(0, this.record.class_map.lastIndexOf(','))
            }
            if (this.record.id) {
              editUrl(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              addUrl(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            }
          } else {
            this.$message({
              message: this.$t('请至少添加一条数据'),
              type: 'error'
            })
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.urlClassList = []
      this.urlList = []
      this.loading = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.multipleTable.clearSelection()
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang="scss" scoped>
.el-switch {
  /deep/ .el-switch__core {
    &::before {
      content: "关";
      color: #fff;
      position: absolute;
      // font-size: 14px;
      transform: scale(0.85);
      left: 20px;
    }
  }

  &.switch-is-actived {
    /deep/ .el-switch__core {
      &::before {
        content: "开";
        left: 5px;
        transform: scale(0.85);
      }
    }
  }
}
</style>
